package Service;

import Dao.*;
import Dao.Impl.*;
import Dto.ArticleDTO;
import Dto.ArticleParamDto;
import entity.Article;
import entity.ArticleAttachment;
import entity.KnowledgeBase;
import exception.BusinessException;
import org.apache.commons.fileupload.FileItem;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author Su
 * @Date 2025/4/18 23:21
 * @Version 1.0 （版本号）
 */
public class ArticleService {
    private ArticleDAO articleDAO;
    private ArticleAttachmentDAO attachmentDAO;
    private KnowledgeBaseService knowledgeBaseService;
    private LikeService likeService;
    private LikeDAO likeDAO;
    private KnowledgeBaseDAO knowledgeBaseDAO;
    private KnowledgeBaseMemberDAO knowledgeBaseMemberDAO;

    public ArticleService(Connection connection) {
        this.articleDAO = new ArticleDAOImpl(connection);
        this.attachmentDAO = new ArticleAttachmentDAOImpl(connection);
        this.likeService = new LikeService(connection);
        this.knowledgeBaseService = new KnowledgeBaseService(new KnowledgeBaseDAOImpl(connection),new KnowledgeBaseMemberDAOImpl(connection),new UserDAOImpl(connection));
        this.likeDAO = new LikeDAOImpl(connection);
        this.knowledgeBaseDAO = new KnowledgeBaseDAOImpl(connection);
        this.knowledgeBaseMemberDAO = new KnowledgeBaseMemberDAOImpl(connection);
    }

    public Article createArticle(int knowledgeBaseId, int authorId, String title,
                                 String content, List<FileItem> fileItems)
            throws Exception {

        // 验证用户权限
        if (!knowledgeBaseService.hasAccess(knowledgeBaseId, authorId)) {
            throw new BusinessException("无权在此知识库创建文章");
        }

        // 创建文章
        Article article = new Article();
        article.setKnowledgeBaseId(knowledgeBaseId);
        article.setTitle(title);
        article.setContent(content);
        article.setAuthorId(authorId);

        int articleId = articleDAO.createArticle(article);
        article.setId(articleId);

        // 处理文件上传
        if (fileItems != null && !fileItems.isEmpty()) {
            List<ArticleAttachment> attachments = saveAttachments(articleId, authorId, fileItems);
            article.setAttachments(attachments);
        }

        return article;
    }

    private List<ArticleAttachment> saveAttachments(int articleId, int uploaderId,
                                                    List<FileItem> fileItems) throws Exception {

        List<ArticleAttachment> savedAttachments = new ArrayList<>();
        String uploadDir = "C:/Users/csl/Desktop/feishu_project(1)/feishu_project/uploads/articles/" + articleId + "/";

        // 创建上传目录
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            boolean created = dir.mkdirs(); // 必须检查是否创建成功
            if (!created) {
                throw new IOException("无法创建目录: " + dir.getAbsolutePath());
            }
        }

        for (FileItem item : fileItems) {
            String originalFileName = new File(item.getName()).getName();
            System.out.println("图片名称" + originalFileName);
//            String fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
//            String storedFileName = System.currentTimeMillis() + fileExtension;
//            String filePath = uploadDir + storedFileName;
            String filePath = uploadDir + originalFileName;

            // 保存文件
            item.write(new File(filePath));

            // 保存附件信息
            ArticleAttachment attachment = new ArticleAttachment();
            attachment.setArticleId(articleId);
            attachment.setFileName(originalFileName);
            attachment.setFilePath(filePath);
            attachment.setFileType(item.getContentType());
            attachment.setFileSize(item.getSize());
            attachment.setUploaderId(uploaderId);

            int attachmentId = attachmentDAO.createAttachment(attachment);
            attachment.setId(attachmentId);
            savedAttachments.add(attachment);
        }

        return savedAttachments;
    }

    public ArticleDTO getArticleWithPermissions(int articleId, int userId)
            throws BusinessException, SQLException {

        ArticleDTO article = articleDAO.getArticleById(articleId);
        if (article == null) {
            throw new BusinessException("文章不存在");
        }
        String content = article.getContent();
        content = content.replace("articleId", String.valueOf(article.getId()));
        article.setContent(content);
        // 验证权限
        if (!knowledgeBaseService.hasAccess(article.getKnowledgeBaseId(), userId)) {
            throw new BusinessException("无权查看此文章");
        }

        // 获取附件,暂时不实现这个功能
//        List<ArticleAttachment> attachments = attachmentDAO.getAttachmentsByArticle(articleId);
//        article.setAttachments(attachments);
        //查看文章点赞
        Integer likeCounts = likeDAO.getLikeCounts(articleId);
        article.setLikeCount(likeCounts);
        //查看当前用户是否点赞
        boolean liked = likeDAO.hasLiked(articleId, userId);
        article.setLiked(liked);
        return article;
    }

    public List<ArticleDTO> getArticlesByKnowledgeBase(int knowledgeBaseId, int userId)
            throws BusinessException, SQLException {

        // 验证权限
        if (!knowledgeBaseService.hasAccess(knowledgeBaseId, userId)) {
            throw new BusinessException("无权访问此知识库");
        }

        List<ArticleDTO> articles = articleDAO.getArticlesByKnowledgeBase(knowledgeBaseId);
        for (ArticleDTO article : articles) {
            List<ArticleAttachment> attachments = articleDAO.getAttachmentsByArticle(article.getId());
//            article.setAttachments(attachments);
        }
        return articles;
    }

    public List<ArticleDTO> getAllArticles(int currentUserId, ArticleParamDto articleParam) throws SQLException {
        List<ArticleDTO> articles = articleDAO.getAllArticles(currentUserId,articleParam);
        for (ArticleDTO article : articles) {
            // 检查当前用户是否点赞
            if (currentUserId > 0) {
                System.out.println("进入检查当前用户是否点赞");
                boolean liked = likeService.hasLiked(article.getId(), currentUserId);
                System.out.println(liked);
                article.setLiked(liked);
            }
        }
        return articles;
    }

    public Article updateArticle(Integer id,int knowledgeBaseId, int authorId, String title,
                                 String content, List<FileItem> fileItems)
            throws Exception {

        // 验证用户权限
        if (!knowledgeBaseService.hasAccess(knowledgeBaseId, authorId)) {
            throw new BusinessException("无权在此知识库修改文章");
        }

        // 创建文章
        Article article = new Article();
        article.setKnowledgeBaseId(knowledgeBaseId);
        article.setTitle(title);
        article.setContent(content);
        article.setAuthorId(authorId);
        article.setId(id);
        //更新文章内容
        articleDAO.updateArticle(article);

        // 处理文件上传
        if (fileItems != null && !fileItems.isEmpty()) {
            List<ArticleAttachment> attachments = saveAttachments(id, authorId, fileItems);
            article.setAttachments(attachments);
        }

        return article;
    }

    public boolean deleteArticle(Integer articleId,Integer knowledgeBaseId,Integer creatorId) throws SQLException, BusinessException{

        // 1、验证知识库存在
        KnowledgeBase kb = knowledgeBaseDAO.findById(knowledgeBaseId);
        if (kb == null) {
            throw new BusinessException("知识库不存在");
        }
        //2、用户是知识库其中成员 是creater
        boolean result = knowledgeBaseMemberDAO.isMember(knowledgeBaseId, creatorId);
        if (!result) {
            throw new BusinessException("无权删除此文章");
        }

        return articleDAO.deleteArticle(articleId);
    }

}
